import { EntityManager, MikroORM } from '@mikro-orm/core';
import { InjectEntityManager, InjectMikroORM } from '@mikro-orm/nestjs';
import { Body, Controller, Get, Param, Post, Put } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { JsonApiResponse } from '@utils/json.api.response';
import { knext } from 'knext';
import { LeFitmentPage } from '@databases/entities/leadshop/LeFitmentPage';
import dayjs from 'dayjs';

@Controller('pages')
export class PagesController {
    constructor(
        private readonly configService: ConfigService,
        @InjectMikroORM('leadshop')
        private readonly orm: MikroORM,
        @InjectEntityManager('leadshop')
        private readonly em: EntityManager, 
    ){}

    @Get('/diy_page/:id')
    async getDiyPage(@Param() id) {
         let knex = knext(this)
         let page = await knex.fromORM(LeFitmentPage).where({id:58}).getOne()

        let pageInfo = {
            page_data:{
                created_time: dayjs().unix(),
                name: "新建微页面",
                title: "1668929958651",
                updated_time: dayjs().unix(),
                background: "#F7F7F7",
                deleted_time: null,
                goods_number: 0,
                visit_number: 0,
                status: 1,
                is_deleted: 0,
                type: "0",
                id: "58",
            },
            items: page.content
        }
        
        return JsonApiResponse.object(pageInfo)
    }

    @Put('/diy_page/:id')
    async saveDiyPage(@Param('id') id,@Body() pageForm) {
         let knex = knext(this)

         // pageForm.contents = JSON.stringify(pageForm.items)
         const result = await knex.fromORM(LeFitmentPage)
         .update({
            // name : pageForm.pageInfo.name,
            // title : pageForm.pageInfo.title,
            updated_time : dayjs().unix(),
            // background : pageForm.pageInfo.background,
            content: JSON.stringify(pageForm.items)
         })
         .where('id',id) 

         return JsonApiResponse.object(result)
    }
}
